package com.chengh.nami.core.security.handler;

import com.chengh.nami.core.async.AsyncManager;
import com.chengh.nami.core.async.factory.AsyncFactory;
import com.chengh.nami.core.security.service.TokenService;
import com.chengh.nami.common.constants.Constants;
import com.chengh.nami.common.domain.model.LoginUserEntity;
import com.chengh.nami.common.response.R;
import com.chengh.nami.common.utils.ResultUtils;
import com.chengh.nami.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义注销成功处理器
 * 登出后应该让前端清除掉token
 *
 * @author chengh
 */
@Component
@RequiredArgsConstructor
public class UserLogoutSuccessHandler implements LogoutSuccessHandler {


    private final TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        LoginUserEntity selUser = tokenService.getSelUser(request);
        if (!StringUtils.isNull(selUser)) {
            String username = selUser.getUsername();
            // 删除用户缓存
            tokenService.delSelUser(selUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGOUT, "退出成功"));
        }
        ResultUtils.responseJson(response, R.ok());
    }
}
